package com.taoshen.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Map;

/**
 * @Description JWT获取token 以及验证token的工具类
 * @Author Zhang Litao
 * @Date 2021/11/18 10:31
 */
public class JWTUtils {
    // 生成token的秘钥
    private static final String SECRET = "yongyuanbusi";

    /**
     * 生成token 形参接收payLoad载荷信息
     */
    public static String getToken(Map<String, Object> payloadMap) {
        // 获取一个JWT构建器
        JWTCreator.Builder builder = JWT.create();

        // 设置形参中payload的内容
        payloadMap.forEach((k, v) -> builder.withClaim(k, v.toString()));

        // 设置过期时间为2小时
        builder.withExpiresAt(DateUtil.offsetHour(DateUtil.date(), 2));

        return builder.sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 验证token是否正确
     */
    public static void verifyToken(String token) {
        JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }

    /**
     * 获取token中的payload 载荷信息
     */
    public static Map<String, Object> getPayload(String token) {
        DecodedJWT jwt = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        String decodeStr = Base64.decodeStr(jwt.getPayload());
        return JSONUtil.toBean(decodeStr, Map.class);
    }
}